package com.tanhua.recommend.com.tanhua.recommend.listener;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.model.domain.Log;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.mongo.VideoScore;
import org.bson.types.ObjectId;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

/**
 * @author Xiao
 * @version 1.0
 * @description 视频消息监听器
 * @date 2021/11/6
 */
@Component
public class RecommendVideoListener {
    @Autowired
    private MongoTemplate mongoTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(
                    value = "tanhua.video.queue",
                    durable = "true"
            ),
            exchange = @Exchange(
                    value = "tanhua.log.exchange",
                    type = ExchangeTypes.TOPIC),
            key = {"log.video"})
    )
    public void recommend(String message) {
        //解析数据
        Log log = JSON.parseObject(message, Log.class);
        if (ObjectUtil.isEmpty(log)) {
            return;
        }
        try {
            String busId = log.getBusId();
            Video video = mongoTemplate.findById(new ObjectId(busId), Video.class);
            //构造VideoScore，设置评分
            if (ObjectUtil.isNotEmpty(video)) {
                VideoScore videoScore = new VideoScore();
                videoScore.setUserId(log.getUserId());
                videoScore.setVideoId(video.getVid());
                videoScore.setScore(getScore(log.getType()));
                videoScore.setDate(System.currentTimeMillis());
                System.err.println(videoScore);
                //保存到数据库
                mongoTemplate.insert(videoScore);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Double getScore(String type) {
        //0301为发小视频，0302为小视频点赞，0303为小视频取消点赞，0304为小视频评论
        Double score = 0d;
        switch (type) {
            case "0301":
                score=2d;
                break;
            case "0302":
                score=5d;
                break;
            case "0303":
                score = -5d;
                break;
            case "0304":
                score = 10d;
                break;
            default:
                break;
        }
        return score;
    }
}
